<template>
  <div ref="chartContainer" class="star-chart-container"></div>
</template>

<script setup>
import { ref, onMounted,inject } from 'vue';
import * as echarts from 'echarts';
import { scorePeopleNum } from '@/api/shouyePub.js';

const cc = inject("id") //获取父组件传递的值

const chartContainer = ref(null); // 定义图表容器
let chartInstance = null; // 定义图表实例

// 示例数据
const chartData = ref({
  stars: ['1星', '2星', '3星', '4星', '5星'],
  values: [20, 50, 30, 80, 45] // 对应每个星级的人数
});

//查出酒店不同评分的人数并赋值
const scoreNum = async ()=>{
  const res = await scorePeopleNum(cc);
  console.log(res.data.data)
  chartData.value.values = res.data.data
}

// 图表配置
const initChart = () => {
  const option = { // 设置图表配置

    tooltip: {  // 设置提示框
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '0%',
      top:'1%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '人数',
      axisLabel: {  // 设置x轴标签样式
        color: '#999',
      }
    },
    boundaryGap: false, // 消除边界间隙
    yAxis: {
      type: 'category',
      data: chartData.value.stars,
      axisLabel: {  // 设置y轴标签样式
        color: '#999',
        fontSize: 14
      },
      inverse: true // 使星级从上到下排列
    },
    series: [{
      name: '人数',
      type: 'bar',
      data: chartData.value.values,
      barWidth: 15, // 直接设置固定宽度（单位：像素）
      itemStyle: { // 设置柱状图颜色
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#188df0' }
        ]),
      },
      emphasis: {  // 设置鼠标悬停时的样式
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      },
      label: { // 设置柱状图上方显示的数值
        show: true,
        position: 'right',
        color: '#188df0'
      }
    }]
  };
  chartInstance.setOption(option);
};

// 生命周期
onMounted(async () => {
  chartInstance = echarts.init(chartContainer.value);//初始化容器 监听窗口大小变化，重新渲染图表
  await scoreNum()
  initChart();
});
</script>

<style scoped>
.star-chart-container {
  width: 500px;
  float: right;
  height: 200px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  padding: 20px;
  box-sizing: border-box;
}
</style>